import React, { useState } from "react";
import { useDispatch } from "react-redux";
import {
  useGetFoodQuery,
  // useDeleteFoodMutation,
  // useUpdateFoodMutation
} from "../../slices/foodApiSlice";
import Loader from "../../components/pages/Loader";
import { addItemToCart } from "../../slices/cartReducer";
import Header from "../../components/pages/Header";
import Footer from "../../components/pages/Footer";
import toast from "react-hot-toast";
import { Pizza } from "lucide-react";

/**
 * FoodList 组件用于显示食品列表
 * 该组件从 API 获取食品数据，并提供食品项的渲染、编辑和删除功能
 */
const FoodList = () => {
  // 使用 Redux 的 dispatch 函数来分发动作
  const dispatch = useDispatch();
  // 使用 useGetFoodQuery 钩子来获取食品数据，包括数据、错误、加载状态和重新获取数据的函数
  const { data, error, isLoading, refetch } = useGetFoodQuery();

  // 使用状态管理来跟踪当前正在编辑的食品项的 ID 和表单数据
  const [editing, setEditing] = useState(null);
  const [editFormData, setEditFormData] = useState({
    name: "",
    description: "",
    price: "",
  });

  // 定义编辑食品项的处理函数
  const handleEditClick = (food) => {
    setEditing(food._id);
    setEditFormData({
      name: food.name,
      description: food.description,
      price: food.price,
    });
  };

  // 定义编辑表单数据变化的处理函数
  const handleEditChange = (e) => {
    const { name, value } = e.target;
    setEditFormData({ ...editFormData, [name]: value });
  };

  // 定义编辑表单提交的处理函数
  const handleEditSubmit = async (e) => {
    e.preventDefault();
    try {
      //await updateFood({ id: editing, ...editFormData }).unwrap();
      setEditing(null);
      toast.success("Food item updated");
      refetch();
    } catch (error) {
      console.error("Error updating food item", error);
      toast.error("Error updating food item");
    }
  };

  // 定义删除食品项的处理函数
  const handleDeleteClick = async (id) => {
    try {
      //await deleteFood(id).unwrap();
      toast.success("Food item deleted");
      refetch();
    } catch (error) {
      console.error("Error deleting food item", error);
      toast.error("Error deleting food item");
    }
  };

  // 定义添加食品项到购物车的处理函数
  const addToCartHandler = (food) => {
    dispatch(addItemToCart(food));
  };

  // 定义渲染食品项为卡片的函数
  const renderFoodAsCards = (foods) => (
    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
      {foods.map((food) => (
        <div key={food._id} className="bg-background p-4 rounded-lg shadow-2xl">
          <div className="flex flex-col justify-between h-full">
            <div className="flex-grow">
              <img
                src={food.image}
                alt={food.name}
                className="w-full h-62 object-cover rounded mb-4"
              />
              <h2 className="text-xl font-semibold text-primary dark:text-primary-dark">
                {food.name}
              </h2>
              <p>{food.description}</p>
              <p>${food.price}</p>
            </div>
            <div className="flex space-x-2 mt-4">
              <button
                className="bg-primary text-background px-4 py-2 rounded hover:bg-primary dark:hover:bg-red-600"
                onClick={() => addToCartHandler(food)}
              >
                Add to Cart ${food.price}
              </button>
              {/*<button*/}
              {/*  className="bg-primary text-background px-4 py-2 rounded hover:bg-primary dark:hover:bg-red-600"*/}
              {/*  onClick={() => handleEditClick(food)}*/}
              {/*>*/}
              {/*  Edit*/}
              {/*</button>*/}
              {/*<button*/}
              {/*  className="bg-primary text-background px-4 py-2 rounded hover:bg-primary dark:hover:bg-red-600"*/}
              {/*  onClick={() => handleDeleteClick(food._id)}*/}
              {/*>*/}
              {/*  Delete*/}
              {/*</button>*/}
            </div>
          </div>
        </div>
      ))}
    </div>
  );

  // 根据数据加载状态显示加载组件或错误信息
  if (isLoading) return <Loader />;
  if (error) return <div>Error loading food items</div>;

  // 提取食品数据
  const foods = data?.data || [];

  // 渲染组件
  return (
    <>
      <Header />
      <div className="container mx-auto p-4 bg-background text-text dark:bg-background-dark dark:text-text-dark">
        <h1 className="text-4xl font-bold mb-4 mt-24 text-center text-primary dark:text-primary-dark flex items-center justify-center gap-2">
          <Pizza size={32} />
          Food List
        </h1>

        {foods.length > 0 ? (
          renderFoodAsCards(foods)
        ) : (
          <p className="text-gray-700 dark:text-gray-300">No food items available.</p>
        )}

      </div>
      <Footer />
    </>
  );
};

export default FoodList;
